<?php

class TareaEtapaController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @var bool the type of menu
     */
    public $admin = true;

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new TareaEtapa;

        $this->performAjaxValidation($model, 'tarea-etapa-form');

        if (isset($_POST['TareaEtapa'])) {
            $model->attributes = $_POST['TareaEtapa'];
            $model->estado = TareaEtapa::ESTADO_ACTIVO;

            if ($model->save()) {
                $this->redirect(array('admin'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        $this->performAjaxValidation($model, 'tarea-etapa-form');

        if (isset($_POST['TareaEtapa'])) {
            $model->attributes = $_POST['TareaEtapa'];
            if ($model->save()) {
                $this->redirect(array('admin'));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('TareaEtapa');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new TareaEtapa('search');
        $model->unsetAttributes(); // clear any default values
        $probabilidad = TareaEtapa::model()->findAll(array("condition" => "porcentaje = :porcentaje and estado=:estado", "params" => array(":porcentaje" => TareaEtapa::PORCENTAJE_100, ':estado' => TareaEtapa::ESTADO_ACTIVO)));



//            die();
        if (empty($probabilidad)) {//solo si existe en la consulta datos es porq hay valores con 100%
            Yii::app()->user->setFlash('error', ' No existe una etapa que refleje el 100%');
        }

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = TareaEtapa::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'tarea-etapa-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function sortable($idSort, $pesoS, $idRep, $pesoR) {
        $modelEtap = TareaEtapa::model()->getEtapas();
        $ban = FALSE;
        if ($pesoS > $pesoR) {
            foreach ($modelEtap as $etap) {
                if ($etap['id'] == $idRep || $ban) {
                    $etap['peso'] = $etap['peso'] + 1;
                    TareaEtapa::model()->updateByPk($etap['id'], array('peso' => $etap['peso']));
                    if ($etap['id'] == $idSort) {
                        TareaEtapa::model()->updateByPk($etap['id'], array('peso' => $pesoR));
                        $ban = false;
                    } else {
                        $ban = TRUE;
                    }
                }
            }
        } else if ($pesoS < $pesoR) {
            $ba2 = false;
            foreach ($modelEtap as $etap) {
                if ($etap['id'] == $idSort) {
                    TareaEtapa::model()->updateByPk($etap['id'], array('peso' => $pesoR));
                    $ba2 = TRUE;
                } else if ($ba2) {
                    if ($etap['id'] == $idRep) {
                        $etap['peso'] = $etap['peso'] - 1;
                        TareaEtapa::model()->updateByPk($etap['id'], array('peso' => $etap['peso']));
                        $ba2 = FALSE;
                    } else {
                        $etap['peso'] = $etap['peso'] - 1;
                        TareaEtapa::model()->updateByPk($etap['id'], array('peso' => $etap['peso']));
                    }
                }
            }
        }
    }

    /**
     * Manages all models.
     */
    public function actionReordenar() {
        $model = new TareaEtapa();
        if (isset($_POST)) {
            $id_sort = $_POST['dragged_item_id'];
            $id_repl = $_POST['replacement_item_id'];

            $pesoSort = TareaEtapa::model()->findByPk($id_sort)->peso;
            $pesorepl = TareaEtapa::model()->findByPk($id_repl)->peso;
            $this->sortable($id_sort, $pesoSort, $id_repl, $pesorepl);
            $this->render('admin', array(
                'model' => $model,
            ));
        }
    }

}
